package com.xiangwei.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;

import com.xiangwei.controller.ProductController;
import com.xiangwei.entity.Product;
import com.xiangwei.entity.Vendor;
import com.xiangwei.service.IQrcodeService;

public class FileOperation {

	private static String filePath;
	private static final Logger logger = LoggerFactory.getLogger(ProductController.class);
	/**
	 * 创建文件
	 * 
	 * @param fileName
	 * @return
	 */
	public static boolean createFile(File fileName) throws Exception {
		boolean flag = false;
		try {
			if (!fileName.exists()) {
				fileName.createNewFile();
				flag = true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return true;
	}

	/**
	 * 读TXT文件内容
	 * 
	 * @param fileName
	 * @return
	 */
	public static String readTxtFile(File fileName) throws Exception {
		String result = null;
		FileReader fileReader = null;
		BufferedReader bufferedReader = null;
		try {
			fileReader = new FileReader(fileName);
			bufferedReader = new BufferedReader(fileReader);
			try {
				String read = null;
				while ((read = bufferedReader.readLine()) != null) {
					result = result + read + "\r\n";
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (bufferedReader != null) {
				bufferedReader.close();
			}
			if (fileReader != null) {
				fileReader.close();
			}
		}
//		System.out.println("读取出来的文件内容是：" + "\r\n" + result);
		return result;
	}

	/**
	 * txt文件写入
	 * @param content
	 * @param fileName
	 * @return
	 * @throws Exception
	 */
	public static boolean writeTxtFile(String content, File fileName)
			throws Exception {
		boolean flag = false;
		FileOutputStream o = null;
		try {
			o = new FileOutputStream(fileName);
			o.write(content.getBytes("GBK"));
			o.close();
			flag = true;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			e.printStackTrace();
		} finally {
			if (o != null) {
				o.close();
			}
		}
		return flag;
	}

	/**
	 * 拼接内容
	 * 
	 * @param filePath
	 * @param content
	 */
	public static void contentToTxt(String filePath, String content) {
		String str = new String(); // 原有txt内容
		String s1 = new String();// 内容更新
		try {
			File f = new File(filePath);
			if (!f.exists()) {
				f.createNewFile();// 不存在则创建
			}
			BufferedReader input = new BufferedReader(new FileReader(f));

			while ((str = input.readLine()) != null) {
				s1 += str + "\n";
			}
			input.close();
			s1 += content;

			BufferedWriter output = new BufferedWriter(new FileWriter(f));
			output.write(s1);
			output.close();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			e.printStackTrace();
		}
	}

	/**
	 * 先批量插入数据库，再从数据库中获取ID集合，然后批量拼接写到txt中
	 * */
	@Transactional
	public static String contentToTxtByThread(IQrcodeService iqrcodeService, String code, Vendor vendor,
			Product product, Integer count, String filepath, String QRCodeURL,String addNum) {
		int maxCount = 0;
		int num = 100000;
		String createTime = DateUtils.getStringFullDate();//创建时间

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("productId", code);	
		String path = null;
		
		if(count > num){//判断生成数量是否大于两百万
			int size = count / num;
			int surplus = count - size*num;
			for(int a=0; a<size; a++){
				maxCount = iqrcodeService.getMaxId(map);//获取表中最大ID
				int[] ids = new int[num];
				for(int i = 0;i <num;i++){
					ids[i]=i+1+maxCount;
				}
				
				//添加二维码
				map.put("numList", ids);
				iqrcodeService.bathchInsert(map);
				filePath = filepath;
				Map<String,Object> idMap = new HashMap<String,Object>(); 
				idMap.put("maxCount", maxCount);
				idMap.put("productId", code);
				List<Integer> idList = iqrcodeService.getIdList(idMap);
				path = getTxt(idList,code,vendor,product,
						maxCount,num,createTime,QRCodeURL,addNum);
//				System.out.println(path);				
			}
			if(surplus > 0){
				maxCount = iqrcodeService.getMaxId(map);//获取表中最大ID
				int[] ids = new int[surplus];
				for(int i = 0;i <surplus;i++){
					ids[i]=i+1+maxCount;
				}
				
				//添加二维码
				map.put("numList", ids);
				iqrcodeService.bathchInsert(map);
				filePath = filepath;
				Map<String,Object> idMap = new HashMap<String,Object>(); 
				idMap.put("maxCount", maxCount);
				idMap.put("productId", code);
				List<Integer> idList = iqrcodeService.getIdList(idMap);
				path = getTxt(idList,code,vendor,product,
						maxCount,surplus,createTime,QRCodeURL,addNum);
//				System.out.println(path);
				
			}
			return path;
		}
		
			
		maxCount = iqrcodeService.getMaxId(map);//获取表中最大ID
		int[] ids = new int[count];
		for(int i = 0;i <count;i++){
			ids[i]=i+1+maxCount;
		}
		
		//添加二维码
		map.put("numList", ids);
		iqrcodeService.bathchInsert(map);
		filePath = filepath;			    
	    
		Map<String,Object> idMap = new HashMap<String,Object>(); 
		idMap.put("maxCount", maxCount);
		idMap.put("productId", code);
		List<Integer> idList = iqrcodeService.getIdList(idMap);		
		path = getTxt(idList,code,vendor,product,
				maxCount,count,createTime,QRCodeURL,addNum);
//		System.out.println(path);
		return path;
}

	
	public static String getTxt(List<Integer> idList,String code,Vendor vendor,Product product,
			int maxCount,int count,String createTime,String QRCodeURL,String addNum){
		DESUtil des = new DESUtil("xiangwei");
		if(idList.size()>0){
//			String monthBatch = code;
			//写文件
			// 文件路径为“://”+厂商名称+“//”+文件名称为产品名称_当前日期+"//"+生成数量.txt
			filePath = filePath+ File.separator + vendor.getVName()+"_" +product.getPName()+"_"+ createTime + File.separator;
			filePath = filePath + (maxCount+1) + "_" + (maxCount+count) + ".txt";
			String s1 = new String();// 内容更新
			try {
				File f = new File(filePath);
				if (!f.getParentFile().exists()) {
					f.getParentFile().mkdirs();// 不存在则创建文件夹
				}
				if (!f.exists()) {
					f.createNewFile();
				}
				BufferedWriter output = new BufferedWriter(new FileWriter(f,true));
				
				for(int j=0; j<count; j++){
					//ticket的参数=产码批次(明文2位)+概率批次(明文1位)+二维码id(加密) 
					//eg:1+02+sfdhasfhsdfjo, 1+12+sdhasidajsd
					String i = idList.get(j).toString();
					int length = 8-i.length();
					for (int k = 0; k < length; k++) {
						i = "0"+i;
					}
					//加密
					s1 = des.encryptStr(idList.get(j)+"");
//					s1 = QRCodeURL+"?"+code+s1+","+qrcode.get("monthBatch").toString().toUpperCase()+i+"\r\n";
					int length1 = 4-code.length();
					for (int k = 0; k < length1; k++) {
						code = "0"+code;
					}
					
					s1 = QRCodeURL+"?"+code+s1;
					if(Common.isEmptyString(addNum) && Integer.parseInt(addNum) == 1){
						s1 = s1+","+i;
					}
					s1 = s1 + "\r\n";
					output.write(s1);
				}
				output.close();
				return filePath;
			} catch (Exception e) {
				e.printStackTrace();
			}
		return null;
	}
		return null;
	}
	

	
}